class Picklist < ApplicationRecord
  belongs_to :user

  has_many :picklist_songs
  has_many :songs, through: :picklist_songs

  def toggle_song(song_id)
    if picklist_songs.exists?(song_id: song_id)
      picklist_songs.where(song_id: song_id).destroy_all
      'destroy'
    else
      if picklist_songs.count >= 500
        oldest = picklist_songs.order(updated_at: :asc).limit(1)[0]
        oldest.update(song_id: song_id)
      else
        picklist_songs.create(song_id: song_id)
      end
      'create'
    end
  end
end
